/**
  * Validate form with it's action via ajax, and display messages at it's place. Use with struts' form and inputs tag
  * Validation messages looks like this:
  *	{ "fieldErrors": {"name":["Name is required"]}}
  * or like stuts json with comments
  *
  */
function validate(form, onSuccess) {
	var url = jQuery(form).attr("action")+'?&struts.enableJSONValidation=true';
	
	var dataStr = jQuery(form).serialize();

	jQuery.ajax({
			type: "POST",
			url: url,
			data: dataStr,
			dataType: "text",
			async: false,
			success: function(data) {
				try {
					var success = true;
					/*
					 * Clear all error messages
					 */
					jQuery(form).find("li").removeClass('error');
					jQuery(form).find("div[class='errorMessage']").remove();
					
					/*
					 * If there was error
					 */
					if(data.length > 0) {
						if(data.match(/\/\*.*\*\//) != null) {
							data = data.replace(/\/\*/,"").replace(/\*\//,"");
						}
						var objects = jQuery.parseJSON(data);
						jQuery.each(objects.fieldErrors,function(i, v) {
							success=false;
							jQuery(form).find("[name='" + i + "']").after('<div class="errorMessage">'+v+'</div>');
							jQuery(form).find("[name='" + i + "']").parent().addClass("error");
							jQuery(form).find("[name='" + i + "']").focus();
						});
					}
					jQuery(form).find("input[type='submit']").each(function() {
						jQuery(this).removeAttr("disabled");
					});
					if(success == true) {
						try {
							onSuccess();
						} catch(e) {}
					}				
					return false;
				} catch(e) {alert(e);}
			},
			beforeSend: function(data) {
				jQuery(form).find(".input[type='submit']").each(function() {
					jQuery(this).attr("disabled", true);
				});
			} 
		});
	return false
}
